#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import logging
import logging.handlers


class ColoredFormatter(logging.Formatter):
    '''重构的格式化类，参考自https://www.cnblogs.com/perfe/p/6604250.html'''

    def __init__(self, fmt=None, datefmt=None):
        logging.Formatter.__init__(self, fmt, datefmt)
        self.colors_format = {
            'DEBUG': "{}",
            'INFO': "\033[1;32m{}\033[0;0m",
            'WARNING': "\033[1;33m{}\033[0;0m",
            'ERROR': "\033[1;31m{}\033[0;0m",
            'CRITICAL': "\033[1;31m{}\033[0;0m",
        }

    def format(self, record):
        level_name = record.levelname
        msg = logging.Formatter.format(self, record)

        return self.colors_format.get(level_name, '{}').format(msg)


class Logger():
    def __init__(self, log_file_name="", log_level=logging.INFO, logger_name=__file__, log_format="", verbose=True,
                 colorful=True, max_bytes=104857600, backup_count=1):
        '''
            指定保存日志的文件路径，日志级别，以及调用文件
            将日志存入到指定的文件中
            %(name)s            Name of the logger (logging channel)
            %(levelno)s         Numeric logging level for the message (DEBUG, INFO,
                                WARNING, ERROR, CRITICAL)
            %(levelname)s       Text logging level for the message ("DEBUG", "INFO",
                                "WARNING", "ERROR", "CRITICAL")
            %(pathname)s        Full pathname of the source file where the logging
                                call was issued (if available)
            %(filename)s        Filename portion of pathname
            %(module)s          Module (name portion of filename)
            %(lineno)d          Source line number where the logging call was issued
                                (if available)
            %(funcName)s        Function name
            %(created)f         Time when the LogRecord was created (time.time()
                                return value)
            %(asctime)s         Textual time when the LogRecord was created
            %(msecs)d           Millisecond portion of the creation time
            %(relativeCreated)d Time in milliseconds when the LogRecord was created,
                                relative to the time the logging module was loaded
                                (typically at application startup time)
            %(thread)d          Thread ID (if available)
            %(threadName)s      Thread name (if available)
            %(process)d         Process ID (if available)
            %(message)s         The result of record.getMessage(), computed just as
                                the record is emitted
        '''
        if log_format == "":
            log_format = '[%(levelname)s] %(asctime)s - %(name)s - %(funcName)s - %(lineno)d - %(message)s'

        # 创建一个logger
        self.logger = logging.getLogger(logger_name)
        self.logger.setLevel(log_level)

        # 定义handler的输出格式
        formatter = logging.Formatter(log_format)

        # 创建一个handler，用于写入日志文件
        if log_file_name:
            if log_file_name[-4:] != ".log":
                log_file_name += ".log"

            fh = logging.handlers.RotatingFileHandler(log_file_name, maxBytes=max_bytes, backupCount=backup_count)
            fh.setFormatter(formatter)
            fh.setLevel(log_level)
            self.logger.addHandler(fh)
            # fh = logging.FileHandler(log_file_name)
            # fh.setFormatter(formatter)
            # fh.setLevel(log_level)
            # self.logger.addHandler(fh)

        if verbose == True:
            # 再创建一个handler，用于输出到控制台
            ch = logging.StreamHandler()
            ch.setLevel(log_level)
            if colorful == True:
                if sys.platform == "win32" and os.getenv("TERM") != "xterm":
                    # 不定义颜色
                    pass
                else:
                    # 定义handler的输出格式，带颜色
                    color_formatter = ColoredFormatter(log_format)
                    ch.setFormatter(color_formatter)
            else:
                ch.setFormatter(formatter)
            self.logger.addHandler(ch)

    def getlog(self):
        return self.logger


def unitTestLogger():
    import os
    logger = Logger(log_file_name=os.path.splitext(__file__)[0]+".log", logger_name=__file__, verbose=True)
    logh = logger.getlog()
    logh.debug("i am sad")
    logh.info("i am sad")
    logh.warning("i am sad")
    logh.error("i am sad")
    logh.critical("i am sad")


if __name__ == "__main__":
    unitTestLogger()